//
//  Cell.swift
//  GameOfLife
//
//  Created by LLZ on 16/8/1.
//  Copyright © 2016年 ucsmy. All rights reserved.
//

import UIKit

class Cell{
    var x:Int = 0
    var y:Int = 0
    var isAlive:Bool = false
    var neighbourNum:Int = 0
    var cellView:UIView = UIView()
    
    
    init() {
        cellView.frame = CGRectMake(0, 0, cellLength, cellLength)
        cellView.backgroundColor = UIColor.orangeColor()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Cell.announceLocation(_:)), name: "Evolution_AnnounceLocation", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Cell.update(_:)), name: "Evolution_Update", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Cell.othersLocation(_:)), name: "Cell_AnnounceLocation", object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "Evolution_AnnounceLocation", object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "Cell_AnnounceLocation", object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "Evolution_Update", object: nil)
    }
    
    @objc private func announceLocation(noti:NSNotification) {
        if self.isAlive {
            NSNotificationCenter.defaultCenter().postNotificationName("Cell_AnnounceLocation", object: self)
        }
    }
    
    @objc private func othersLocation(noti:NSNotification) {
        if let cell = noti.object as? Cell {
            
            if (cell.x == (self.x - 1) && cell.y == (self.y - 1)) ||
                (cell.x == self.x && cell.y == (self.y - 1)) ||
                (cell.x == (self.x + 1) && cell.y == (self.y - 1)) ||
                (cell.x == (self.x - 1) && cell.y == self.y) ||
                (cell.x == (self.x + 1) && cell.y == self.y) ||
                (cell.x == (self.x - 1) && cell.y == (self.y + 1)) ||
                (cell.x == self.x && cell.y == (self.y + 1)) ||
                (cell.x == (self.x + 1) && cell.y == (self.y + 1)) {
                neighbourNum += 1
            }
        }
    }
    @objc private func update(noti:NSNotification) {
        if self.neighbourNum == 3 {
            self.isAlive = true
            self.cellView.backgroundColor = UIColor.orangeColor()
        } else if self.neighbourNum != 2 {
            self.isAlive = false
            self.cellView.backgroundColor = UIColor.init(red: 170/255.0, green: 170/255.0, blue: 170/255.0, alpha: 1)
        }
        
        self.neighbourNum = 0
    }
}



